package com.lzh.crypt.ase;

import com.lzh.crypt.enums.AesAlgorithmEnum;
import com.lzh.crypt.enums.CryptAlgorithmEnum;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.security.Security;

/**
 * @author zhehen.lu
 * @date 2025/8/10 19:56
 */
public class AESKeyPair {

    private SecretKey secretKey;

    private String cryptAlgorithm = "AES";

    private AESKeyPair() {

    }

    private AESKeyPair(SecretKey secretKey, String cry) {
        this.secretKey = secretKey;
        this.cryptAlgorithm = cry;
    }

    public static AESKeyPair instance(byte[] key) {
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, AesAlgorithmEnum.AES.getAlgorithm());
        AESKeyPair aesKeyPair = new AESKeyPair(secretKeySpec, CryptAlgorithmEnum.AES.getAlgorithm());
        return aesKeyPair;
    }

    public static AESKeyPair instance(byte[] key, AesAlgorithmEnum cryptAlgorithm) {
        Security.addProvider(new BouncyCastleProvider());
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, AesAlgorithmEnum.AES.getAlgorithm());
        AESKeyPair aesKeyPair = new AESKeyPair(secretKeySpec, cryptAlgorithm.getAlgorithm());
        return aesKeyPair;
    }

    public byte[] encrypt(byte[] content) throws Exception {
        Cipher cipher = Cipher.getInstance(cryptAlgorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] secContent = cipher.doFinal(content);
        return secContent;
    }

    public byte[] decrypt(byte[] secContent) throws Exception {
        Cipher cipher = Cipher.getInstance(cryptAlgorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] content = cipher.doFinal(secContent);
        return content;
    }

    public static byte[] genericKey(int size) throws Exception {
        KeyGenerator generator = KeyGenerator.getInstance(CryptAlgorithmEnum.AES.getAlgorithm());
        generator.init(size, SecureRandom.getInstanceStrong());
        SecretKey secretKey = generator.generateKey();
        return secretKey.getEncoded();
    }

}
